import { loginApi, userApi, userInfoById } from '@/api/user'
import { setToken, getToken, removeToken, setTimeStamp } from '@/utils/auth'
export default {
  namespaced: true,
  state: {
    token: getToken(),
    userInfo: {}
  },
  // 设置token
  mutations: {
    setToken(state, token) {
      state.token = token
    },
    setUserInfo(state, data) {
      state.userInfo = data
    },
    removeToken(state) {
      state.token = null
      removeToken()
    },
    // 清除用户信息
    removeUserInfo(state) {
      state.userInfo = {}
    }
  },
  actions: {
    // 退出登录
    logout(ctx) {
      ctx.commit('removeToken')
      ctx.commit('removeUserInfo')
    },
    // 获取用户信息
    async getUserInfo(ctx) {
      const res = await userApi()
      const res1 = await userInfoById(res.userId)
      // console.log(res1)
      // console.log(res)
      ctx.commit('setUserInfo', { ...res, ...res1 })
    },
    // 登录
    async login(ctx, data) {
      const res = await loginApi(data)
      // console.log(res)
      // 存储token
      ctx.commit('setToken', res)
      // token 持久化
      setToken(res)
      setTimeStamp()
    }
  }
}
